import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;



public class Util {
	public static final byte HEADER_VALUE_BYTE1 = (byte) 0xC4;
	public static final byte HEADER_VALUE_BYTE2 = 0x61;
	public static final String ADDRESS = "http://homes.cs.washington.edu/~yuxuan/shawnserverip/getipport.php";
	
	
	/**
	 * Read the type of the given data array.
	 */
	public static int readType(byte[] data) {
		return data[3] & 0xFF;
	}
	
	public static byte readSeqNumber(byte[] data) {
		return data[2];
	}
	
	public static byte[] generateHeader(int seqNum, int type, int length) {
		byte[] ret = new byte[length];
		ret[0] = HEADER_VALUE_BYTE1;
		ret[1] = HEADER_VALUE_BYTE2;
		ret[2] = (byte) (seqNum & 0xFF);
		byte b = (byte) (type & 0xFF);
		ret[3] = b;
		return ret;
	}
	
	public static void printUsage() {
		System.out.println("Usage: ");
		System.out.println("\t Register:   r serviceName portnum data");
		System.out.println("\t Unregister: u serviceName");
		System.out.println("\t Fetch:      f <name prefix>");
		System.out.println("\t Probe:      p");
		System.out.println("\t Help:       h");
		System.out.println("\t Force Quit: q");
		System.out.println("\t Quit:       q!");
	}
	
	public static String getIpFromByteArray(byte[] data, int startPoint) {
		String ipString = ((int) (data[0 + startPoint] & 0xFF)) + "";
		for (int i = 1; i < 4; i++) {
			ipString += "." + ((int) (data[i + startPoint] & 0xFF));
		}
		return ipString;
	}
	
	public static long getLongFromTwoBytes(byte[] data, int startPoint) {
		return ((long) (data[startPoint] & 0xFF) << 8) + ((long) (data[startPoint + 1] & 0xFF)) ;
	}
	
	public static long getLongFromFourBytes(byte[] data, int startPoint) {
		return ((long) (data[startPoint] & 0xFF) << 24) + ((long) (data[startPoint + 1] & 0xFF) << 16) 
				+ ((long) (data[startPoint + 2] & 0xFF) << 8) + ((long) (data[startPoint + 3] & 0xFF)) ;
	}
	
	public static String getCommandTypeInEnglish (int type) {
		if (type == 0x01) {
			// Register
			return "Register";
		} else if (type == 0x03) {
			// Fetch
			return "Fetch";
		} else if (type == 0x05) {
			// Unregister
			return "Unregister";
		} else if (type == 0x06) {
			// Probe
			return "Probe";
		} else {
			return "Unknown Command";
		}
	}
	
	public static String getOutAddressPort() throws Exception {
		String ret = "";
        URL ip = null;
        ip = new URL(ADDRESS);
        URLConnection yc = null;
		yc = ip.openConnection();
        BufferedReader in = null;
        in = new BufferedReader(
			                        new InputStreamReader(
			                        yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
        	ret += inputLine;
        
		in.close();
        return ret;
	}
}
